<?php
namespace Hive\Contact\Import\Format\Reader;
/**
 * Contact Import File Reader
 * Handle format translation
 *
 * @property int	$format		Format id
 * @property string	$language	Language
 * @property string	$label		Label
 */
class Csv {

	/**
	 * 
	 * Read the file expecting a spreadsheet 
	 * @param string $filename
	 * @param \Hive\Contact\Import\Format
	 */
	public static function read($filename,$format) {
		$limit = $format->row_limit;
		$delimiter = $format->delimiter;
		$references = $errors = $data = array();
		// Open and Read File
		$rowCount = 1;
		$fields = $format->items();
		if (($handle = fopen($filename, 'r')) !== FALSE) {
			
		    while (($rowData = fgetcsv($handle, 1000,$delimiter)) !== FALSE) {
		    	if($rowCount == 1) {
		    		$rowCount++;
		    		continue;
		    	}
		    	$lineData = null;
			    foreach($fields as $id => $item) {
			    	$attribute = $item->attribute;
			    	if(empty($attribute)) {
			    		continue;
			    	}
			    	$colNumber = $item->col_number;
			    	$column = $item->col_number - 1;
					// Get Cell Value
					if(!isset($rowData[$column])) {
						// File Format Error
						$errors[] = Msg(\Hive::BUNDLE,\Hive::ERR_EMPY_FIELD_IN_ROW_COLUMN,$rowCount,$colNumber,$item->label());
						break;
					}
					$value = str_replace('"','',$rowData[$column]);
					// Check if the item is mandatory
					if($item->mandatory > 0 && empty($value)) {
						$errors[] = Msg(\Hive::BUNDLE,\Hive::ERR_EMPY_FIELD_IN_ROW_COLUMN,$rowCount,$colNumber,$item->label());
						break;
					}
					// Parse Value & Check Format
					switch ($item->datatype) {
						// Alpha numeric
						case 1:
							break;
						// Alpha numeric
						case 3:
							break;
						// Do nothing
						default;
					}
					$lineData[$item->attribute] = $value;
					// Reference Data Line
					$reference[$item->reference][$item->sequence][$item->attribute] = $value;
				}
				if(is_array($lineData)) {
					$data[] = $lineData;
					$references[] = $reference;
				}
		    }
		    fclose($handle);
		}
		return array('data' => $data,'errors' => $errors,'references' => $references);
	}
}